<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/10/11
 * Time: 8:43
 */

namespace app\worker\controller;


use app\common\model\Member;
use app\common\model\Message;
use app\library\traits\ResponceJson;
use think\Controller;
use think\Db;
use think\facade\Session;
use think\Request;

class Index extends Controller
{
    use ResponceJson;
    public function index()
    {
        return $this->view->fetch();
    }

    public function test()
    {
        return $this->view->fetch();
    }

    public function t()
    {
        dump(Session::get());
    }

    /**
     * 用户类表
     * 1.获取当前进入用户的session
     */
    public function talklist(Request $request)
    {
        $User = Session::get('user_auth');


        $this->assign([
            'userId'=>$User['uid'],
            'userName'=>$User['username'],
        ]);
        return $this->view->fetch();
    }

    public function message(Request $request)
    {
        $formId = $request->param('formid');
        $this->assign([
            'formId'=>$formId
        ]);
        return $this->view->fetch();
    }

    /**
     * 获取对话列表
     * @param Request $request
     */
    public function getTalkList(Request $request)
    {
        $formid = $request->param('formid');
        if($formid){
            $list = Db::name('message')
                ->alias('m')
                ->join('__MEMBER__ u','u.id=m.formid','LEFT')
                ->field("m.formid,m.toid,m.type,u.username,u.avatar")
                ->where(['toid'=>$formid])
                ->group('m.toid')
                ->select();
            foreach ($list as $key => $value) {
                $list[$key]['last'] = $this->getLastMessage($formid);
                $list[$key]['no_read_num'] = $this->getNoReadNum($formid);
            }

            if($list){
                return json($this->jsonSuccess($list));
            }
        }
    }

    /**
     * 获取最后一条信息
     */
    public function getLastMessage($formId)
    {
        $info = Db::name('message')->where(['toid'=>$formId])->order('create_time DESC')->find();
        return $info;
    }

    /**
     * 获取未读消息数量
     * @param $fromId
     */
    public function getNoReadNum($formId)
    {
        $num = Db::name('message')->where(['formid'=>$formId,'is_read'=>0])->count();
        if($num>0){
            return $num;
        } else {
            return 0;
        }
    }

    public function talk(Request $request)
    {
        $User = Session::get();

        $formId = $request->param('formid'); //发送者ID
        $toId   = $request->param('toid'); //发送给谁



        $this->assign([
            'formId'=>$formId,
            'toId'=>$toId
        ]);

        return $this->view->fetch();
    }

    public function userlist(Request $request)
    {
        $roomId = $request->param('roomid'); //加入的分组（房间）
        $this->assign([
            'roomId'=>$roomId,
        ]);
        return $this->view->fetch();
    }

    /**
     * 聊天室
     * 1.聊天室只需要formid，接收方为所有人
     * @return string
     * @throws \Exception
     */
    public function room(Request $request)
    {
        $formId = $request->param('formid'); //发送者ID
        $roomId = $request->param('roomid'); //加入的分组（房间）
        // 获取个人信息
        $Member = new Member();
        $userInfo = $Member->info($formId,true,4);
        $this->assign([
            'formId'=>$formId,
            'roomId'=>$roomId,
            'userInfo'=>$userInfo
        ]);
        return $this->view->fetch();
    }

    /**
     * 获取数据，存入数据库
     */
    public function save_message(Request $request)
    {
        $formId         = $request->post('formid');
        $toId           = $request->post('toid');
        $content        = $request->post('content');
        $is_read        = $request->post('is_read');
        $create_time    = time();

        $data = [
            'formid'=>$formId,
            'toid'=>$toId,
            'content'=>$content,
            'type'=>1,
            'is_read'=>$is_read,
            'create_time'=>$create_time
        ];

        $Message = new Message();
        $result = $Message->post_message($data);

        if($result){
            return json($this->jsonSuccess());
        }
    }

    public function getUserInfo(Request $request)
    {
        $formId = $request->param('formid');
        $toId   = $request->param('toid');
        $Member = new Member();
        $formUser   = $Member->info($formId,true,4);
        $toUser     = $Member->info($toId,true,4);
        $data = [
            'form_avatar'=>$formUser['avatar'],
            'to_avatar'=>$toUser['avatar']
        ];
        return json($this->jsonSuccess($data));
    }

    /**
     * 获取历史聊天记录
     */
    public function load_message(Request $request)
    {
        $formId = $request->param('formid');
        $toId   = $request->param('toid');
        $where[] = ['formid','in',array($formId,$toId)];
        $where[] = ['toid','in',array($formId,$toId)];
        $page = $request->param('page')?$request->param('page'):1;
        $list = Db::name('message')->where($where)->page($page,10)->order('id DESC')->select();
        return json($this->jsonSuccess(array_reverse($list)));
    }

    /**
     * 上传图片
     */
    public function upload_pic(Request $request)
    {
        $data = [
            'formid'=>$request->param('formId'),
            'toid'=>$request->param('toId'),
            'type'=>2,
            'is_read'=>$request->param('is_online'),
            'create_time'=>time()
        ];

        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('pic');
        // 移动到框架应用根目录/uploads/ 目录下
        $info = $file->move( './uploads');

        if($info){
            // 成功上传后 获取上传信息
            $data['content'] = '/uploads/'.str_replace('\\','/',$info->getSaveName());
        }else{
            // 上传失败获取错误信息
            echo $file->getError();
        }

        $Message = new Message();
        $result = $Message->post_message($data);

        if($result){
            return json($this->jsonSuccess('/uploads/'.str_replace('\\','/',$info->getSaveName())));
        }
    }
}